<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleAddSubmit" :form="form">
        <a-form-item
          label="添加模式"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-tag color="#428bca" @click="checkMode()" v-if="!this.check">切换为扫码模式</a-tag>
          <a-tag color="#428bca" @click="checkMode()" v-else>切换为选择模式</a-tag>
        </a-form-item>
        <a-form-item
          label="商品"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
          v-if="!this.check"
        >
          <!-- <a-select v-decorator="['goodId']" show-search placeholder="请选择">
            <a-select-option :value="i.id" v-for="i in this.prodOption" :key="i.value">{{ i.name }}</a-select-option>
          </a-select> -->
          <a-select
            show-search
            :value="value ? value : undefined"
            :placeholder="`请至少输入一个字符`"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="handleChange"
          >
            <a-select-option v-for="d in prodOption" :key="d.inventoryId">
              {{ d.goodName }} {{ d.phoneCode1 }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="串码"
          v-else
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-textarea
            rows="8"
            placeholder="可添加多个,每行一个串码，错误的串码会被过滤掉"
            v-decorator="['phoneCodeList', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" title="调货商品清单">
      <a-table ref="table" size="default" rowKey="key" :columns="columns" :data-source="loadData">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="submitform">
        <a-form-item
          label="调往门店"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['inStore',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择">
            <a-select-option :value="i.id" v-for="i in this.storeOption" :key="i.value">{{
              i.storeName
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="调库日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker v-decorator="['outDate', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" style="width: 100%" valueFormat="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input v-decorator="['memo']" name="memo" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">提交调货</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>
    
  <script>
import { getInventoryListByPhoneCdeUsingGET, getInventoryListUsingGET } from '@/api/api/pifayewu.ts'
import { getStoreListUsingPOST } from '@/api/api/mendianguanli.ts'
import { addStoreAdjustUsingPOST } from '@/api/api/diaoku.ts'
import moment from 'moment'
export default {
  name: 'CounterId',
  data() {
    return {
      check: false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      value: undefined,
      toDays: moment().format('YYYY-MM-DD'),
      form: this.$form.createForm(this),
      submitform: this.$form.createForm(this),
      prodOption: [],
      storeOption: [],
      queryParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      columns: [
        {
          title: '商品',
          dataIndex: 'goodName',
        },
        {
          title: '串码',
          dataIndex: 'phoneCode1',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
    }
  },
  created() {
    this.getStoreOption()
  },
  methods: {
    handleDel(record) {
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这个商品吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loadData.splice(
            that.loadData.findIndex((item) => item.id === record.id),
            1
          )
          // this.loadData = this.loadData
        },
      })
    },
    handleSearch(value) {
      this.handleProd(value)
    },
    handleChange(value) {
      this.value = value
    },
    removeTrim(array) {
      for (let i = 0; i < array.length; i++) {
        if (array[i] == '') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    handleProd(params) {
      getInventoryListByPhoneCdeUsingGET({
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
        storeId: this.$route.params.id,
        phoneCodeStr: params,
      })
        .then((res) => {
          this.prodOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    getStoreOption() {
      getStoreListUsingPOST(this.optionParam)
        .then((res) => {
          this.storeOption = res.data.list.filter(item => item.id != this.$route.params.id )
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleAddSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.check) {
            getInventoryListUsingGET({
              pageNo: 1,
              pageSize: 99999,
              phoneCodeList: this.removeTrim(values.phoneCodeList.split('\n')).toString(),
              status: 1,
              inCounterId: this.$route.params.counterId,
              storeId: this.$route.params.id,
            })
              .then((res) => {
                const data = res.data.list.map((item, index) => {
                  return {
                    ...item,
                    phoneCode1: values.phoneCodeList.split('\n')?.[index],
                  }
                })
                const includes = this.loadData.some((i) => data?.map((j) => j.phoneCode1)?.includes(i.phoneCode1))
                if (!!includes) {
                  this.$message.error('存在相同串码')
                } else {
                  this.loadData = this.loadData.concat(data)
                }
              })
              .catch((error) => {
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            const includes = this.loadData
              .map((item) => item.phoneCode1)
              .includes(
                this.prodOption.find((item) => {
                return item.inventoryId == this.value
              }).phoneCode1
              )
            if (!!includes) {
              this.$message.error('存在相同串码')
              return false
            }
            this.loadData.push({
              ...values,
              phoneCode1: this.prodOption.find((item) => {
                return item.inventoryId == this.value
              }).phoneCode1,
              goodName: this.prodOption.find((item) => {
                return item.inventoryId == this.value
              }).goodName,
              goodId: this.prodOption.find((item) => {
                return item.inventoryId == this.value
              }).goodId,
            })
          }
        }
      })
    },
    // handler
    checkMode() {
      this.check = !this.check
    },
    handleSubmit(e) {
      e.preventDefault()
      this.submitform.validateFields((err, values) => {
        if (!err) {
          if(this.loadData.length == 0) {
            this.$message.error('没有可调库的商品')
            return false
          }
          const params = {
            adjustListParams: this.loadData.map((item) => {
              return {
                goodId: item.goodId,
                phoneCode1: item.phoneCode1,
              }
            }),
            memo: values.memo,
            outDate: values.outDate,
            inStore: values.inStore,
            outStore: this.$route.params.id,
          }
          addStoreAdjustUsingPOST({...params})
            .then((res) => {
              this.$message.success('操作成功')
              this.$router.push({ path: `/shift/shopShiftRecord/detail/${res.data.id}` })
              // this.$router.push({ path: `/shift/shopShift/index` })
              // 重置表单数据
              this.form.resetFields()
              this.submitform.resetFields()
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
  },
}
</script>